package com.yint.tree;

import java.util.List;

/**
 * 随机性复合节点
 * <p>
 * 随机选取一个子节点tick
 * <p>
 * Created by 殷田 on 2018/5/3.
 */
public class Random extends Composite {

    @Override
    protected synchronized STATUS onTick(Tree tree) {
        List<Leaf> subs = getSubs();
        if (subs != null && subs.size() > 0) {
            int index = (int) (Math.random() * subs.size());
            if (index > subs.size() - 1) {
                index = subs.size() - 1;
            }
            Leaf sub = subs.get(index);
            if (sub.entry(tree)) {
                return sub.tick(tree);
            } else {
                sub.leave(tree);
            }
        }
        return STATUS.FAILED;
    }
}
